package controllers;

import play.db.jpa.JPA;
import play.mvc.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import models.*;

import javax.persistence.EntityManager;
import javax.persistence.criteria.*;

public class Application extends Controller {

    public static void index() {
        ta001("20080201", null, null, null, null, 100);
    }

    public static void ta001(String dateStart,
                             String dateEnd,
                             String aircraft,
                             String smi,
                             String flight_id,
                             Integer pageSize) {

        aircraft = aircraft!=null ? aircraft.toUpperCase() : null;
        smi = smi!=null ? smi.toUpperCase() : null;
        flight_id = flight_id!=null ? flight_id.toUpperCase() : null;

        String contains = params.get("contains");
        contains = contains!=null ? contains.toUpperCase() : null;

        Date start = null;
        Date end = null;
        if (dateStart != null && !dateStart.isEmpty()) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                start = dateFormat.parse(dateStart);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (dateEnd != null && !dateEnd.isEmpty()) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                end = dateFormat.parse(dateEnd + "235959");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (pageSize == null) {
            pageSize = 30;
        }
        List<TA001> msgs = TA001.filterBy(start, end, aircraft, smi, flight_id, contains, pageSize);

        Long maxResults = TA001.maxResultsFilterBy(start, end, aircraft, smi, flight_id, contains);

        render(msgs, dateStart, dateEnd, aircraft, smi, flight_id, contains, pageSize, maxResults);
    }

    public static void ta002() {
        List<TA002> items = TA002.find("order by id desc").fetch(10);

        render(items);
    }

    public static void ta001view(long id) {
        TA001 result = TA001.findById(id);

        List<TA002> ta002 = TA002.find("msg_id=?", result.getMsg_id()).fetch();

        Map<String, Object> map = new HashMap();
        map.put("msg", result);
        map.put("ta002", ta002);
        renderTemplate(map);
    }

    public static void ta002view(long id) {
        TA002 entity = TA002.findById(id);

        TA001 ta001 = (TA001)TA001.find("msg_id = ?", entity.msg_id).fetch().get(0);

        render(entity, ta001);
    }

    public static void ta015xml(Long id) {
        TA015 entity = TA015.findById(id);

        renderXml(entity.template);
    }
}

